{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sum of Dependencies in a graph\n",
    "- Given a directed and connected graph with n nodes.\n",
    "- If there is an edge from u to v then u depends on v.\n",
    "\n",
    "Find the sum of dependencies for every node.\n",
    "\n",
    "## Example\n",
    "\n",
    "![](http://d1hyf4ir1gqw6c.cloudfront.net//wp-content/uploads/flipkartinterview1-300x204.png)\n",
    "\n",
    "- A depends on C and D\n",
    "- B depends on D\n",
    "- C depends on D\n",
    "- D depends on none\n",
    "- So answer is 2 + 1 + 1 = 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Graph():\n",
    "    def __init__(self, size):\n",
    "        self.data = []\n",
    "        for i in xrange(size):\n",
    "            self.data.append([])\n",
    "            \n",
    "    def addEdge(self, u, v):\n",
    "        self.data[u].append(v)\n",
    "        \n",
    "    def sum_of_dependencies(self):\n",
    "        count = 0\n",
    "        for i in self.data:\n",
    "            count += len(i)\n",
    "        return count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[], [], [], []]\n"
     ]
    }
   ],
   "source": [
    "g = Graph(4)\n",
    "print g.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2, 3], [3], [2], []]\n"
     ]
    }
   ],
   "source": [
    "g.addEdge(0, 2)\n",
    "g.addEdge(0, 3)\n",
    "g.addEdge(1, 3)\n",
    "g.addEdge(2, 2)\n",
    "print g.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "print g.sum_of_dependencies()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Resources\n",
    "- http://www.geeksforgeeks.org/sum-dependencies-graph/"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
